package com.n9.buymsg.service.qqonline;

import com.n9.buymsg.AppContext;
import com.n9.buymsg.event.QQMsgCountEvent;
import com.n9.buymsg.service.qqonline.converter.FilterChain;
import com.n9.buymsg.service.qqonline.converter.MsgConverter;
import com.n9.buymsg.service.qqonline.converter.PurchaseMessageConverter;
import com.n9.qq.android.AqContext;
import com.n9.qq.android.mock.MsgListener;
import com.n9.qq.android.msg_comm.Msg;
import com.n9.sdk.model.PurchaseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 消息监听器
 * @Author: ice
 * @Date: 2020-07-02 18:18
 */
public class DefaultMsgListener implements MsgListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMsgListener.class);

    private MsgConverter msgConverter = new PurchaseMessageConverter();

    private static Map<Long, AtomicLong> qqMsgCounter = new ConcurrentHashMap<>();//QQ消息计数器


    @Override
    public void onReceived(Msg msg, AqContext context) {
        Optional<PurchaseMessage> optional = msgConverter.convert(msg, context);

        optional.ifPresent(pMsg -> {
            try {
                countMsg(pMsg);
                FilterChain filterChain = FilterChainFactory.create();
                filterChain.doFilter(pMsg);
            } catch (Exception e) {
                LOGGER.error("处理消息异常:{}", e.getMessage());
            }
        });
    }


    /**
     * 消息计数
     * @param pMsg
     */
    private void countMsg(PurchaseMessage pMsg) {
        String receiver = pMsg.getReceiver();
        if (Objects.isNull(receiver)) {
            return;
        }

        long qqUin = Long.parseLong(receiver);
        AtomicLong atomicLong = qqMsgCounter.get(qqUin);
        if (Objects.isNull(atomicLong)) {
            atomicLong = new AtomicLong(0);
            qqMsgCounter.put(qqUin, atomicLong);
        }
        long curCount = atomicLong.incrementAndGet();
       AppContext.getInstance().publishEvent(QQMsgCountEvent.createNewMsgEvent(qqUin, curCount));
    }
}
